package com.sicnu.comments.controller;

import com.sicnu.comments.entity.CommentsDO;
import com.sicnu.comments.entity.CommentVO;
import com.sicnu.comments.entity.res.Result;
import com.sicnu.comments.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/comments")
public class CommentsController {

    @Autowired
    private CommentService commentService;

    @PostMapping("/add")
    public Result<CommentsDO> addComment(@RequestBody CommentsDO comment) {
        CommentsDO savedComment = commentService.addComment(comment);
        if (savedComment != null) {
            return Result.buildSuccess(savedComment);
        } else {
            return Result.buildFailure("添加评论失败");
        }
    }

    @GetMapping("/listByResource/{resourceId}")
    public Result<List<CommentVO>> getCommentsByResourceId(@PathVariable Integer resourceId) {
        List<CommentVO> comments = commentService.getCommentTree(resourceId);
        return Result.buildSuccess(comments);
    }

    @DeleteMapping("/delete/{commentId}")
    public Result<Void> deleteComment(@PathVariable Integer commentId) {
        boolean success = commentService.removeById(commentId);
        if (success) {
            return Result.buildSuccess();
        } else {
            return Result.buildFailure("删除评论失败");
        }
    }

    @PutMapping("/update")
    public Result<CommentsDO> updateComment(@RequestBody CommentsDO comment) {
        boolean success = commentService.updateById(comment);
        if (success) {
            return Result.buildSuccess(comment);
        } else {
            return Result.buildFailure("更新评论失败");
        }
    }
}